package com.vivien.example.springbootdemo.controller;

import com.vivien.example.springbootdemo.dto.JwtResponse;
import com.vivien.example.springbootdemo.pojo.User;
import com.vivien.example.springbootdemo.security.JwtTokenProvider;
import com.vivien.example.springbootdemo.service.UserService;
import com.vivien.example.springbootdemo.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "http://localhost:8848")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user) {
        try {
            return ResponseEntity.ok(new JwtResponse(userService.login(user)));
        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }
    // 注册接口
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        try {
            // 调用 Service 层进行注册操作
            userService.register(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            return Result.error("注册失败: " + e.getMessage());
        }
    }
}